/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package koor.servlet;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import koor.action.Action;
import koor.action.ActionManager;
import koor.action.ActionResult;
import koor.action.student.*;
import koor.action.user.UserAddAction;
import koor.action.user.UserDeleteAction;
import koor.action.user.UserListAction;
import koor.action.user.UserSaveAction;
import koor.authorization.UserAuthorisation;
import koor.entity.User;
import koor.hibernate.HibernateUtil;
import koor.persistent.*;
import koor.service.ServiceLocator;

/**
 * The
 * <code>MainServlet</code> servlet performs all actions in system, except log
 * in and log out
 *
 * @author Admin
 */
public class MainServlet extends HttpServlet {

    private ActionManager actionManager;
    private static String USER_AUTH = "userAuth";

    @Override
    public void init() throws ServletException {

        DaoFactory daoFactory = new DAOFactoryImpl();
        ServiceLocator.registerService(ActionDAO.class, daoFactory.getActionDAO());
        ServiceLocator.registerService(CourseWorkDAO.class, daoFactory.getCourseWorkDAO());
        ServiceLocator.registerService(DepartmentDAO.class, daoFactory.getDepartmentDAO());
        ServiceLocator.registerService(RoleDAO.class, daoFactory.getStudentDAO());
        ServiceLocator.registerService(SubjectDAO.class, daoFactory.getSubjectDAO());
        ServiceLocator.registerService(TagDAO.class, daoFactory.getTagDAO());
        ServiceLocator.registerService(TeacherDAO.class, daoFactory.getTeacherDAO());
        ServiceLocator.registerService(TextDAO.class, daoFactory.getTextDAO());
        ServiceLocator.registerService(UserDAO.class, daoFactory.getUserDAO());

        actionManager = new ActionManager();
        actionManager.addAction(new StudentListAction());
        actionManager.addAction(new StudentAction());
        actionManager.addAction(new StudentCreateAction());
        actionManager.addAction(new StudentDeleteAction());
        actionManager.addAction(new StudentEditAction());
        actionManager.addAction(new StudentSaveAction());
        actionManager.addAction(new StudentSearchAction());

        actionManager.addAction(new UserListAction());
        actionManager.addAction(new UserAddAction());
        actionManager.addAction(new UserSaveAction());
        actionManager.addAction(new UserDeleteAction());

        //actionManager.addAction(new DefaultAction());
    }

    @Override
    public void destroy() {
        HibernateUtil.shutdown();
    }

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        String actionName = request.getParameter("action");
        boolean loginAction = false;

        if ((actionName == null) || (actionManager.findAction(actionName) == null)) {
            actionName = "default.action";
        }

        if (actionName.equals("login.view")) {
            loginAction = true;
        }

        if ((request.getSession().getAttribute(USER_AUTH) != null) || loginAction) {
            User user=new User();

            if (!loginAction) {
                user=(((UserAuthorisation) request.getSession().getAttribute(USER_AUTH)).getUser());
            }

            if (ServiceLocator.getService(UserDAO.class).isActionAllowed(user, actionName) || loginAction) {

                Action action = actionManager.findAction(actionName);

                ActionResult forward;
                try {
                    forward = action.execute(request, response);

                    if (forward.isForward()) {
                        RequestDispatcher requestDispatcher = getServletContext()
                                .getRequestDispatcher("/WEB-INF/View/" + forward.getViewJsp());
                        requestDispatcher.forward(request, response);
                    }

                    if (forward.isRedirect()) {
                        response.sendRedirect(request.getContextPath() + "/main?action=" + forward.getAction());
                    }
                } catch (RuntimeException e) {
//                    if (((UserAuthorisation) request.getSession().getAttribute(USER_AUTH)).getUser().getRole().getTitle().equalsIgnoreCase("Администратор")
//                        && (System.getenv("APUS_DB_PATH") == null)) {
//                        RequestDispatcher requestDispatcher = getServletContext()
//                                .getRequestDispatcher("/WEB-INF/View/databaseSettingError.jsp");
//                        requestDispatcher.forward(request, response);
//                    } else {
                        RequestDispatcher requestDispatcher = getServletContext()
                                .getRequestDispatcher("/WEB-INF/View/error.jsp");
                        requestDispatcher.forward(request, response);
//                    }
                } catch (Exception e) {
                    RequestDispatcher requestDispatcher = getServletContext()
                            .getRequestDispatcher("/WEB-INF/View/error.jsp");
                    requestDispatcher.forward(request, response);
                }
            } else {
                RequestDispatcher requestDispatcher = getServletContext()
                        .getRequestDispatcher("/WEB-INF/View/accessDeniedPage.jsp");
                requestDispatcher.forward(request, response);
            }

        } else {
            response.sendRedirect(request.getContextPath() + "/main?action=login.view");
        }
    }
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
